package net.imagine.provider.fastdfs;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerGroup;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

public class StorageClientFactory {
	private static final Log logger = LogFactory.getLog(StorageClientFactory.class);
	private static TrackerGroup trackerGroup;
	
	public static void init(Resource config) {
		try {
			String file = config.getFile().getPath();
			ClientGlobal.init(file);
		} catch (FileNotFoundException e) {
			logger.error("Cannot find FastDFS client config file", e);
		} catch (IOException e) {
			logger.error("Cannot read FastDFS client config file", e);
		} catch (Exception e) {
			logger.error("Cannot read FastDFS client config file", e);
		}
		trackerGroup = ClientGlobal.getG_tracker_group();
	}
	
	public static StorageClient getStorageClient(String groupName) throws IOException {
		if(trackerGroup == null) {
			return null;
		}
		TrackerClient trackerClient = new TrackerClient(trackerGroup);
		TrackerServer trackerServer = trackerClient.getConnection();
		if(trackerServer == null) {
			logger.error("Connect to DFS Tracker Server Failed");
			return null;
		}
		
		StorageServer storageServer = null;
		if(StringUtils.hasText(groupName)) {
			storageServer = trackerClient.getStoreStorage(trackerServer, groupName);
		} else {
			storageServer = trackerClient.getStoreStorage(trackerServer);
		}
		
		if(storageServer == null) {
			logger.error("Connect to DFS Storage Server Failed");
			return null;
		}
		StorageClient storageClient = new StorageClient(trackerServer, storageServer);
		return storageClient;
	} 
}
